package cn.com.dealme.nutz.validation;

import org.apache.commons.validator.Arg;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.util.ValidatorUtils;

import cn.com.dealme.error.ErrorMap;
import cn.com.dealme.error.ErrMsgManager;

public class FieldValidator {
	

	public boolean validateRequired(Object bean, 
									Field field, 
									ValidatorAction action,
									ErrorMap<String, String> errMap) {
		String value = null;
        if (isString(bean)) {
            value = (String) bean;
        } else {
            value = ValidatorUtils.getValueAsString(bean, field.getProperty());
        }

        if (GenericValidator.isBlankOrNull(value)) {
        	Arg arg0 = field.getArg(0);
        	Arg argRequeired = field.getArg(action.getName(), 0);
        	errMap.put(arg0.getKey(), ErrMsgManager.getResource(argRequeired.getKey()));
            return false;
        } else {
            return true;
        }
	}
	
	public boolean validateMinLength(Object bean, 
									 Field field, 
									 ValidatorAction action,
									 ErrorMap<String, String> errMap) {
		String value = null;
        if (isString(bean)) {
            value = (String) bean;
        } else {
            value = ValidatorUtils.getValueAsString(bean, field.getProperty());
        }

        Arg actionArgs = field.getArg(action.getName(), 0);
        String minLengthStr = field.getVar(actionArgs.getKey()).getValue();
        if(Integer.parseInt(minLengthStr) > value.length()) {
        	Arg arg0 = field.getArg(0);
            errMap.put(arg0.getKey(), ErrMsgManager.getResource(actionArgs.getKey()));
            return false;
        }
        return true;
	}
	
	protected static boolean isString(Object o) {
        return (o == null) ? true : String.class.isInstance(o);
    }
	
}
